/*
 * 地区联动插件
 * 2014-03-24 duxcms
 */
(function($) {   
    $.fn.duxArea = function(options) {
    	var defaults = {
			url:''
		}
		var options = $.extend(defaults, options);
		this.each(function(){
			//获取数据
			var wrap=$(this);
			var sel=$("select",wrap);
			var sProvince=sel.eq(0);  
        	var sCity=sel.eq(1);  
        	var sCounty=sel.eq(2);
        	//移除选项节点
        	sProvince.empty();  
	        sCity.empty();  
	        sCounty.empty();
	        //添加数据元素
	        function fillOption(el , type, selectedText){
				switch(type)
				{
				case 1:
				  var parent_id = 1;
				  break;
				case 2:
				  var parent_id = sProvince.val();
				  break;
				case 3:
				  var parent_id = sCity.val();
				  break;
				}
				$.ajax({
					url:options.url,
					data: {parent_id:parent_id},
					async:false,
					dataType:"json",
					success:function(data){
						if(data.status == 'y'){
							 var json = data.info;
							$.each(json , function(k , v) {  
								var option  = '<option value="'+v.region_id+'">'+v.region_name+'</option>';
								if (v.region_id == selectedText) {
									var option    = '<option selected="selected" value="'+v.region_id+'">'+v.region_name+'</option>';  
								}
								el.append(option);
							})
						}else{
							if(type==3){
								var option = '<option selected="selected" value="0">'+sCity.find("option:selected").text()+'</option>'; 
							}else{
								var option = '<option selected="selected" value="0">==请选择==</option>'; 
							}
                    		el.append(option);
						}
					}
				});
	        }
			var selectedData = new Array();
			var selectedStr = wrap.attr('data');
			if(selectedStr != ''){
				selectedData = selectedStr.split(",");
			}
            fillOption(sProvince , 1,  selectedData[0]);  
            fillOption(sCity ,  2, selectedData[1]);
            fillOption(sCounty , 3, selectedData[2]);
	        //选择省
	        sProvince.change(function() {  
		        sCity.empty();
		        fillOption(sCity , 2);  
		        sCounty.empty();  
		        fillOption(sCounty , 3);  
		    })
		    //选择市
		    sCity.change(function() {  
		        sCounty.empty();
		        fillOption(sCounty , 3);
		    })
		    //选择区域
		    sCounty.change(function(){   
		    })
		});
    };
})(jQuery);  